import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:old_shop/common/appbar/appbar.dart';
import 'package:flutter/material.dart';
import 'package:old_shop/common/const/cosnt.dart';
import 'package:old_shop/common/network/network.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:zevent_bus/zevent_bus.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  List<dynamic> data = [];

  @override
  void initState() {
    super.initState();
    _getData();
  }

  void _getData() {
    Networktool.request("v2/list", method: HTTPMETHOD.GET, success: (sender) {
      print("$sender");
      setState(() {
        data.addAll(sender);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            pinned: true,
            backgroundColor: AppColor.mainColor,
            title: CupertinoTextField(
              placeholder: "请输入想要搜的商品名称",
              prefix: Icon(
                Icons.search_sharp,
                size: 24,
                color: Colors.grey,
              ),
            ),
          ),
          SliverPadding(
            padding: const EdgeInsets.all(12),
            sliver: SliverWaterfallFlow(
              gridDelegate: const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext c, int index) {
                  return _Card(model: data[index]);
                },
                childCount: data.length,
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _Card extends StatelessWidget {
  final Map<String, dynamic> model;
  const _Card({Key? key, required this.model}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final double height = size.width * model["height"] / model["width"];
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: height,
          child: PhysicalModel(
            borderRadius: BorderRadius.circular(12),
            clipBehavior: Clip.antiAlias,
            color: Colors.transparent,
            child: CachedNetworkImage(
              imageUrl: model["download_url"],
              fit: BoxFit.cover,
            ),
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              model["author"],
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, height: 28 / 18),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 4, bottom: 4),
              child: Row(
                children: [
                  Icon(
                    Icons.share,
                    color: Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(width: 10),
                  Icon(
                    Icons.message,
                    color: Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(fontSize: 11, color: Colors.grey),
                  ),
                  const SizedBox(width: 10),
                  Icon(
                    int.parse(model["id"]) % 2 == 0 ? Icons.favorite : Icons.favorite_border_sharp,
                    color: int.parse(model["id"]) % 2 == 0 ? Colors.red : Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(fontSize: 11, color: Colors.grey),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                Text(
                  "\$${model["height"] ~/ 100}",
                  style: TextStyle(fontWeight: FontWeight.bold, color: Colors.redAccent, fontSize: 18, height: 28 / 18),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () {
                    EventBus.instance.commit(eventKey: 'add', arg: model);
                    EasyLoading.showToast("已加入购物车");
                  },
                  child: Icon(
                    Icons.add_shopping_cart,
                    size: 16,
                    color: Colors.redAccent,
                  ),
                )
              ],
            )
          ],
        )
      ],
    );
  }
}
